package com.topboya.linker.ui.presenter;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.topboya.linker.R;
import com.topboya.linker.api.ApiRetrofit;
import com.topboya.linker.model.response.DictionaryResponse;
import com.topboya.linker.model.response.TencentLocationResponse;
import com.topboya.linker.ui.base.Presenter.BasePresenter;
import com.topboya.linker.ui.base.activity.BaseActivity;
import com.topboya.linker.ui.view.AddDevicesView;
import com.topboya.linker.utils.LogUtils;
import com.topboya.linker.utils.UIUtils;

import java.io.File;
import java.security.acl.LastOwnerException;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class AddDevicesPresenter extends BasePresenter<AddDevicesView> implements TencentLocationListener {

    private static final String TAG = "AddCustomerPresenter:";

    public AddDevicesPresenter(BaseActivity context) {
        super(context);
    }

    public void getOrgTypeFromDic(String type) {

        mContext.showWaitingDialog(UIUtils.getString(R.string.please_wait));
        ApiRetrofit.getInstance().getOrgTypeFromDic(type)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(orgtyperesponse -> {
                    LogUtils.v(TAG + " getOrgTypeFromDic:" + orgtyperesponse.toString());
                    String success = orgtyperesponse.getMeta().getSuccess();
                    if (null != success && Boolean.parseBoolean(success)) {
//                        获取的是终端类型如：配送商，医院
                        List<DictionaryResponse.Data> listorgtype = orgtyperesponse.getData();
                        LogUtils.v(TAG + listorgtype.toString());
                        getHosLevelFromDic("hos_level", listorgtype);

                    }
                }, this::getOrgError);
    }

    public void getHosLevelFromDic(String type, List<DictionaryResponse.Data> listorgtype) {

        ApiRetrofit.getInstance().getHosLevelFromDic(type)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(hoslevelresopnse -> {
                    mContext.hideWaitingDialog();
                    LogUtils.v(TAG + " hoslevelresopnse:" + hoslevelresopnse.toString());
                    String success = hoslevelresopnse.getMeta().getSuccess();
                    if (null != success && Boolean.parseBoolean(success)) {
                        List<DictionaryResponse.Data> listhosleve = hoslevelresopnse.getData();
                        LogUtils.v(TAG + listhosleve.toString());

                        getAreaFromDic("area",listorgtype, listhosleve);
                    }

                }, this::getOrgError);
    }


    public void getAreaFromDic(String type, List<DictionaryResponse.Data> listorgtype, List<DictionaryResponse.Data> listhosleve) {

        ApiRetrofit.getInstance().getAreaFromDic(type)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(arearesopnse -> {
                    mContext.hideWaitingDialog();
                    LogUtils.v(TAG + " arearesopnse:" + arearesopnse.toString());
                    String success = arearesopnse.getMeta().getSuccess();
                    if (null != success && Boolean.parseBoolean(success)) {
                        List<DictionaryResponse.Data> listarea = arearesopnse.getData();
                        LogUtils.v(TAG + listarea.toString());

                        getView().setPickViewData( listorgtype, listhosleve,listarea);
                    }

                }, this::getOrgError);
    }


    public void getInverseAddressList(String latitude,String longitude) {
        String location = latitude +","+longitude;
        LogUtils.v(TAG + "location:"+location);
        ApiRetrofit.getInstance().getInverseAddressList(location,"1")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(tencentlocationresponse -> {
                    mContext.hideWaitingDialog();
                    LogUtils.v(TAG + " arearesopnse:" + tencentlocationresponse.toString());
                    String success = tencentlocationresponse.getMeta().getSuccess();
                    if (null != success && Boolean.parseBoolean(success)) {
                        String tencentlocationresponses = tencentlocationresponse.getData();
                        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
                        LogUtils.v(TAG + "tencentlocationresponses:"+tencentlocationresponses);
                        TencentLocationResponse.Data data = gson.fromJson(tencentlocationresponses,TencentLocationResponse.Data.class);
                        List<TencentLocationResponse.PoisList> getPois = data.getResult().getPois();
                        LogUtils.v(TAG + data);
                        getView().setLoaction(getPois,latitude,longitude);
                    }

                }, this::getOrgError);
    }


    private void getOrgError(Throwable throwable) {

        LogUtils.v(throwable.getLocalizedMessage());
//        UIUtils.showToast(throwable.getLocalizedMessage());
        LogUtils.v(TAG + "getOrgError:" + throwable.getLocalizedMessage());
        mContext.hideWaitingDialog();

    }


    public void getLocationFromTencent(){

        TencentLocationRequest request = TencentLocationRequest.create();
        request.setInterval(10 *10000);
        request.setRequestLevel(TencentLocationRequest.REQUEST_LEVEL_NAME);
        request.setAllowCache(true);
        TencentLocationManager locationManager = TencentLocationManager.getInstance(mContext);
        int erro = locationManager.requestLocationUpdates(request, this);
        Log.v(TAG,"tencent_map_error:"+erro);

    }

    @Override
    public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {
      // longitude 经度  纬度 latitude

        LogUtils.v(TAG + "tencentLocation"+ tencentLocation.toString());
        LogUtils.v(TAG + "s----->"+ s);
              LogUtils.v(TAG + "latitude:"+ tencentLocation.getLatitude() +"longitude:"+ tencentLocation.getLongitude());
              String location = tencentLocation.getLatitude()+","+tencentLocation.getLongitude();
              getInverseAddressList(String.valueOf(tencentLocation.getLatitude()),String.valueOf(tencentLocation.getLongitude()));
    }

    @Override
    public void onStatusUpdate(String s, int i, String s1) {


    }


    public void upLoadFile(String path) {

        File file = new File(path);

        RequestBody fileRQ = RequestBody.create(MediaType.parse("image/*"), file);
        MultipartBody.Part part =MultipartBody.Part.createFormData("picture", file.getName(), fileRQ);

        ApiRetrofit.getInstance().uploadFile(part)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(upfileresponse -> {
                    mContext.hideWaitingDialog();
                    LogUtils.v(TAG + " upfileresponse:" + upfileresponse.toString());
                    String success = upfileresponse.getMeta().getSuccess();
                    if (null != success && Boolean.parseBoolean(success)) {
                        LogUtils.v(TAG + "upfileresponse:"+upfileresponse.getData().toString());
                        String filePath = upfileresponse.getData().getFilePath();
                        getView().upLoadFileSuc(filePath);

                    }

                }, this::getOrgError);
    }

    public void creatOrg( String orgName, String orgAddress, String orgType, String lat, String lon, String addressJson, String hosLevel, String orgAreaId) {

        ApiRetrofit.getInstance().creatOrg(orgName, orgAddress,orgType,lat,lon,addressJson,hosLevel,orgAreaId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(creatorgresponse-> {
                    mContext.hideWaitingDialog();
                    LogUtils.v(TAG + " creatorgresponse:" + creatorgresponse.toString());
                    String success = creatorgresponse.getMeta().getSuccess();
                    if (null != success && Boolean.parseBoolean(success)) {

                        //创建终端成功
                         getView().creatOrgSuc();

                    }

                }, this::getOrgError);
    }

}
